import { createSlice } from '@reduxjs/toolkit';
import Cookies from 'js-cookie';
import auth from '@/api/auth';

// 从cookie中获取初始状态
const getInitialAuthState = () => {
  const token = Cookies.get('token');
  return {
    isAuthenticated: !!token,
    user: null, // 不再从cookie获取用户信息
    token
  };
};

// 创建auth slice
const authSlice = createSlice({
  name: 'auth',
  initialState: getInitialAuthState(),
  reducers: {
    setAuth: (state, action) => {
      state.isAuthenticated = true;
      state.token = action.payload.token;
      // 只将token保存到cookie，设置7天过期
      Cookies.set('token', action.payload.token, { expires: 7 });
    },
    setUser: (state, action) => {
      state.user = action.payload;
    },
    // 移除fetchUserInfo reducer，异步操作应该在组件或thunk中处理
    clearAuth: (state) => {
      state.isAuthenticated = false;
      state.user = null;
      state.token = null;
      Cookies.remove('token');
    }
  }
});

// 导出actions
export const { setAuth, clearAuth, setUser } = authSlice.actions;

// 导出reducer
export default authSlice.reducer;

// 导出选择器
export const selectAuth = (state) => state.auth;
export const selectIsAuthenticated = (state) => state.auth.isAuthenticated;
export const selectUser = (state) => state.auth.user;
export const selectToken = (state) => state.auth.token;